﻿using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using Didaku.QEngine.Common.Abstracts.Entities;
using Didaku.QEngine.Common.Entities.Collections;
using Didaku.QEngine.Common.Interfaces.Engine;
using Didaku.QEngine.Common.Wrapper;

namespace Didaku.QEngine.Common.Entities
{
    [Serializable]
    public class Workflow : WorkflowInfo, IXmlSerializable, IServiceQueueElement
    {
        public Workflow()
        {
            Ranges = new WorkRangeCollection(0);
        }

        #region Implementation of IXmlSerializable

        public XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
            if (reader.IsEmptyElement)
                return;

            if (!reader.Read())
                throw new XmlException("XmlReader读取异常");

            if (reader.HasAttributes)
            {
                for (int i = 0; i < reader.AttributeCount; i++)
                {
                    reader.MoveToAttribute(i);
                    switch (reader.Name)
                    {
                        case "Id":
                            this.Id = (reader.Value);
                            break;
                        case "Number":
                            this.Number = reader.Value;
                            break;
                        case "Chain":
                            this.Chain = UtilitySerialize.Deserialize<WorkflowNodeCollection>(reader.Value);
                            break;
                        case "Description":
                            this.Description = reader.Value;
                            break;
                    }
                }
            } 
            reader.ReadEndElement();
        }

        public void WriteXml(XmlWriter writer)
        {
            writer.WriteAttributeString("Id", Id);
            writer.WriteAttributeString("Number", Number);
            writer.WriteAttributeString("Chain", UtilitySerialize.Serialize(Chain));
            writer.WriteAttributeString("Description", Description);
        }

        #endregion

        public override string ToString()
        {
            return string.Format("{0}.{1}", Number, Description);
        }

        #region Implementation of IServiceQueueElement

        /// <summary>获得本元素的ID
        /// </summary>
        /// <returns></returns>
        public string GetId()
        {
            return Id;
        }

        /// <summary>队列的元素是否是可用状态。如，业务类型可能不在工作时间范围之内。
        /// </summary>
        /// <returns>
        ///   <c>true</c> if this instance is actived; otherwise, <c>false</c>.
        /// </returns>
        public bool IsActived()
        {
            return true;
        }

        #endregion
    }
}
